from django.http import HttpResponse, JsonResponse, request
from django.shortcuts import render

# Create your views here.
from django.views import View
from redis import Redis
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpeg
        """
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis = get_redis_connection('code')
        redis.setex(uuid, 300, text)

        # 响应图片验证码
        return HttpResponse(image, content_type='image/jpeg')


class SmsView(View):
    def get(self, request, mobile):
        if not mobile:
            return JsonResponse({'code': 300, "errmsg": "手机号为空"})

        image_code: str = request.GET.get('image_code')
        print('image_code', image_code)
        image_code_uuid = request.GET.get('image_code_id')
        try:
            redis: Redis = get_redis_connection('code')
            print(redis)
            image_code_redis = redis.get(image_code_uuid)
            if not image_code_redis:
                return JsonResponse({'code': 400, "errmsg": "验证码过期"})
            image_code_redis = image_code_redis.decode()
            print('image_code_redis', image_code_redis)
            if image_code.lower() != image_code_redis.lower():
                return JsonResponse({'code': 500, "errmsg": "图片验证码错了"})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 600, "errmsg": "网络异常"})
        # - 4 给这个手机号发送短信 第三方
        print("发送短信给", mobile)

        return JsonResponse({'code': 0, "errmsg": "ok"})
